package LeetCode.leetcode39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        backTracking(res, path, candidates, target, 0,0);
        return res;
    }

    public static void backTracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum,int index) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            backTracking(res, path, candidates, target, sum,i);
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }
}
